﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AutoMapper;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework;
using FileManagerGlobal_Library;
using FileManager_Server.BusinessLogic.IRepository_Service;
using FileManager_Server.DataLayer.Castle_Model;
using FileManager_Server.DataLayer.Repository;
using FileManager_Server.ServiceModel.DataTransfer_Model;
using FileManager_Server.ServiceModel.WCF_Args_Model;
using FileManager_Server.Utility;
using Newtonsoft.Json;

namespace FileManager_Server.BusinessLogic.Respository_Service
{
    public class FileService : IFileService
    {

        public FolderResultCollection GetDepartmentFolder()
        {
            var result = new FolderResultCollection();
            try
            {
                //result.FolderCollection = new List<FolderResult>
                //                              {
                //                                  new FolderResult
                //                                      {
                //                                          CreateId = "111",
                //                                          CreateName = "测试",
                //                                          FileName = "综合事务",
                //                                          FilePath = "/综合事务",
                //                                          FileSid = "222",
                //                                          IsFile = false,
                //                                          OwnerId = "111",
                //                                          ParentId = "0"
                //                                      }
                //                              };
                //return result;
                using (var repository = new Repository())
                {
                    var queryResult = repository.GetAll<FileDbModel>(x => !x.ISFILE);
                    if(null != queryResult)
                        result.FolderCollection = Mapper.Map<IList<FileDbModel>, List<FolderResult>>(queryResult);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("GetDepartmentFolder has problem:", ex);
                result.ResultException = BaseExceptionEnum.GetFolderCollectionException;
            }
            return result;
        }

        public FileResultCollection GetFolderFileCollection(FileQueryArgs fileQueryArgs)
        {
            var result = new FileResultCollection();
            try
            {
                //result.FileCollection = new List<FileResult>
                //                            {
                //                                new FileResult
                //                                    {
                //                                        CreateId = "111",
                //                                        CreateName = "测试",
                //                                        FileName = "测试.txt",
                //                                        FilePath="/综合事务",
                //                                        FileSize = "234556",
                //                                        IsFile = true,
                //                                        OwnerId = "111",
                //                                        ParentId = "222"
                //                                    }
                //                            };
                //return result;
                using (var repository = new Repository())
                {
                    var queryResult = fileQueryArgs.IsJustMe
                                          ? repository.GetAll<FileDbModel>(
                                              x =>
                                              x.ISFILE && x.PARENTID.Equals(fileQueryArgs.FolderId) &&
                                              x.CREATORID.Equals(fileQueryArgs.UserId))
                                          : repository.GetAll<FileDbModel>(
                                              x => x.ISFILE && x.PARENTID.Equals(fileQueryArgs.FolderId));
                    if (null != queryResult)
                        result.FileCollection = Mapper.Map<IList<FileDbModel>, List<FileResult>>(queryResult);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("GetFolderFileCollection has problem:", ex);
                result.ResultException = BaseExceptionEnum.GetFolderFileCollectionException;
            }
            return result;
        }

        public void UploadFile(RemoteFileInfo request,FileAttchInfo fileAttchInfo)
        {
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(fileAttchInfo.UserId));
                    var current_folder = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(fileAttchInfo.FolderId));
                    var hasFile = repository.GetSingle<FileDbModel>(x => x.PARENTID.Equals(fileAttchInfo.FolderId) && fileAttchInfo.FileName.Equals(x.FILENAME));
                    if(null != hasFile)
                    {
                        var fileRoles = repository.GetAll<FileRoleDbModel>(x => x.FILESID.Equals(hasFile.FILESID));
                        foreach (var fileRoleDbModel in fileRoles)
                            fileRoleDbModel.Delete();
                        hasFile.Delete();
                    }
                    if (null != current_user && null != current_folder)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_folder.OWNERID));
                        // kill target file, if already exists
                        var folderPath = current_comapny.SHORTNAME + current_folder.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_folder.FILEPATH))
                            folderPath += (@"\" + current_folder.FILENAME);
                        var logPath = folderPath;
                        var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath) + "/" + fileAttchInfo.FileName;
                       // if (System.IO.File.Exists(filePath)) System.IO.File.Delete(filePath);
                        var chunkSize = 2048;
                        var buffer = new byte[chunkSize];
                        using (var writeStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            do
                            {
                                // read bytes from input stream
                                var bytesRead = request.FileByteStream.Read(buffer, 0, chunkSize);
                                if (bytesRead == 0) break;
                                // write bytes to output stream
                                writeStream.Write(buffer, 0, bytesRead);
                            } while (true);
                            // report end
                            writeStream.Close();
                            var fileDbModel = new FileDbModel
                                                  {
                                                      FILESID = Guid.NewGuid().ToString(),
                                                      FILENAME = fileAttchInfo.FileName,
                                                      PARENTID = fileAttchInfo.FolderId,
                                                      FILEPATH = string.IsNullOrEmpty(current_folder.FILEPATH) ? "/" + current_folder.FILENAME : current_folder.FILEPATH,
                                                      FILETYPE = false,
                                                      OWNERID = current_comapny.SID,
                                                      ISSHARE = false,
                                                      ISFILE = true,
                                                      CREATOR = current_user.NAME,
                                                      CREATORID = current_user.SID,
                                                      CREATETIME = DateTime.Now,
                                                      UPDATER = current_user.NAME,
                                                      UPDATERID = current_user.SID,
                                                      UPDATETIME = DateTime.Now,
                                                      FILEMARK = FileUtility.Md5File(filePath),
                                                      FILESORT = 1,
                                                      FILESIZE = fileAttchInfo.Length
                                                  };
                            fileDbModel.Create();
                            var folderRoleCollection = repository.GetAll<FileRoleDbModel>(x => x.FILESID.Equals(fileAttchInfo.FolderId));
                            foreach (var subFileRole in folderRoleCollection.Select(folderRole => new FileRoleDbModel
                                                                                                      {
                                                                                                          FILESID = fileDbModel.FILESID,
                                                                                                          FLAGSID = folderRole.FLAGSID,
                                                                                                          INHERITFILESID = folderRole.INHERITFILESID,
                                                                                                          ISALLOWALLOCATE = true,
                                                                                                          ISCREATE = folderRole.ISCREATE,
                                                                                                          ISDELETE = folderRole.ISDELETE,
                                                                                                          ISINHERIT = true,
                                                                                                          ISOWNER = folderRole.ISOWNER,
                                                                                                          ISREAD = folderRole.ISREAD,
                                                                                                          ISUPDATE = folderRole.ISUPDATE,
                                                                                                          RELATIONID = folderRole.RELATIONID,
                                                                                                          ROLESID = Guid.NewGuid().ToString(),
                                                                                                          ROLETYPE = folderRole.ROLETYPE,
                                                                                                          SETUSERID = folderRole.SETUSERID,
                                                                                                          SETUSERNAME = folderRole.SETUSERNAME
                                                                                                      }))
                            {
                                subFileRole.Create();
                            }
                            var fileLogModel = new FileLogDbModel
                                                   {
                                                       LOGSID = Guid.NewGuid().ToString(),
                                                       LOG = string.Format("上传文件: {0} 成功!", logPath + @"\" + fileAttchInfo.FileName),
                                                       LOGTIME = DateTime.Now,
                                                       LOGTYPE = "上传",
                                                       OBJECTID = fileDbModel.FILESID,
                                                       TARGETNAME = logPath + @"\" + fileAttchInfo.FileName,
                                                       USERID = current_user.SID,
                                                       USERNAME = current_user.NAME
                                                   };
                            fileLogModel.Create();
                        }
                        GC.Collect();
                    }
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("UploadFile has problem:", ex);
            }
        }

        public RemoteFileInfo DownloadFile(DownloadRequest request)
        {
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(request.UserId));
                    var current_file = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(request.FileId));
                    if (null != current_user && null != current_file)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_user.COMPANYID));
                        // kill target file, if already exists
                        var folderPath = current_comapny.SHORTNAME + current_file.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_file.FILEPATH))
                            folderPath += (@"\" + current_file.FILENAME);
                        var logPath = folderPath;
                        var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath) + "/" +
                                       current_file.FILENAME;
                        // get some info about the input file
                        var fileInfo = new FileInfo(filePath);
                        // check if exists
                        if (!fileInfo.Exists) throw new FileNotFoundException("File not found", current_file.FILENAME);
                        // open stream
                        var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                        // return result
                        var downLoadFile = new DownlaodAttchInfo
                                               {
                                                   FileName = current_file.FILENAME,
                                                   Length = fileInfo.Length
                                               };
                                               
                        var result = new RemoteFileInfo
                                         {
                                             JsonData = JsonConvert.SerializeObject(downLoadFile),
                                             FileByteStream = stream
                                         };
                        var fileLogModel = new FileLogDbModel
                                               {
                                                   LOGSID = Guid.NewGuid().ToString(),
                                                   LOG =
                                                       string.Format("下载文件: {0} 成功!", logPath + @"\" + current_file.FILENAME),
                                                   LOGTIME = DateTime.Now,
                                                   LOGTYPE = "下载",
                                                   OBJECTID = current_file.FILESID,
                                                   TARGETNAME = logPath + @"\" + current_file.FILENAME,
                                                   USERID = current_user.SID,
                                                   USERNAME = current_user.NAME
                                               };
                        fileLogModel.Create();
                        return result;
                    }
                    GC.Collect();
                    return null;
                    }
                }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("DownloadFile has problem:", ex);
                throw ex;
            }
        }

        public FileDeleteResult DeleteFileService(FileDeleteArgs fileDeleteArgs)
        {
            var result = new FileDeleteResult();
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(fileDeleteArgs.UserId));
                    var current_file = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(fileDeleteArgs.FileSid));
                    if(current_file != null)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_file.OWNERID));
                        var current_folder = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(current_file.PARENTID)&&x.ISFILE==false);
                        // kill target file, if already exists
                        var folderPath = current_comapny.SHORTNAME + current_folder.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_folder.FILEPATH))
                            folderPath += (@"\" + current_folder.FILENAME);
                        var logPath = folderPath + @"\" + current_file.FILENAME;
                        var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath) +@"\" + current_file.FILENAME;
                        if (CheckUploadingFile(filePath))
                        {
                            result.ResultException = BaseExceptionEnum.FileUploading;
                            return result;
                        }
                        if(File.Exists(filePath))
                        {
                            File.Delete(filePath);
                            current_file.Delete();
                            var fileRoleCollection =
                                repository.GetAll<FileRoleDbModel>(x => x.FILESID.Equals(fileDeleteArgs.FileSid));
                            foreach (var fileRoleDbModel in fileRoleCollection)
                                fileRoleDbModel.Delete();
                            var fileLogModel = new FileLogDbModel
                            {
                                LOGSID = Guid.NewGuid().ToString(),
                                LOG = string.Format("删除文件: {0} 成功!", logPath),
                                LOGTIME = DateTime.Now,
                                LOGTYPE = "删除",
                                OBJECTID = fileDeleteArgs.FileSid,
                                TARGETNAME = logPath,
                                USERID = current_user.SID,
                                USERNAME = current_user.NAME
                            };
                            fileLogModel.Create();
                            result.Result = true;
                        }
                        else
                            result.ResultException = BaseExceptionEnum.DeleteFileNotFileException;
                    }
                    else
                     result.ResultException  = BaseExceptionEnum.DeleteFileNotFileException;
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("DeleteFileService has problem:", ex);
                result.ResultException = BaseExceptionEnum.DeleteFileException;
            }
            return result;
        }

        public FileReNameResult ChangeFileNameService(FileReNameArgs fileReNameArgs)
        {
            var result = new FileReNameResult();
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(fileReNameArgs.UserId));
                    var current_file = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(fileReNameArgs.FileSid));
                    if (current_file != null)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_file.OWNERID));
                        var current_folder = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(current_file.PARENTID) && x.ISFILE == false);
                        var folderPath = current_comapny.SHORTNAME + current_folder.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_folder.FILEPATH))
                            folderPath += (@"\" + current_folder.FILENAME);
                        var logPath = folderPath + @"\" + current_file.FILENAME;
                        var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath) + @"\" + current_file.FILENAME;
                        var newFilePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath) + @"\" + fileReNameArgs.FileNewName;
                        if (CheckUploadingFile(filePath))
                        {
                            result.ResultException = BaseExceptionEnum.FileUploading;
                            return result;
                        }
                        if (File.Exists(filePath))
                        {
                            var fileInfo = new FileInfo(filePath);
                            fileInfo.MoveTo(newFilePath);
                            current_file.FILENAME = fileReNameArgs.FileNewName;
                            current_file.UPDATER = current_user.NAME;
                            current_file.UPDATERID = current_user.SID;
                            current_file.UPDATETIME = DateTime.Now;
                            current_file.Update();
                            var fileLogModel = new FileLogDbModel
                            {
                                LOGSID = Guid.NewGuid().ToString(),
                                LOG = string.Format("修改文件名: {0} 成功!", logPath),
                                LOGTIME = DateTime.Now,
                                LOGTYPE = "重命名",
                                OBJECTID = fileReNameArgs.FileSid,
                                TARGETNAME = logPath,
                                USERID = current_user.SID,
                                USERNAME = current_user.NAME
                            };
                            fileLogModel.Create();
                            result.Result = true;
                        }
                        else
                            result.ResultException = BaseExceptionEnum.NotFindFileException;
                    }
                    else
                        result.ResultException = BaseExceptionEnum.NotFindFileException;
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("ChangeFileNameService has problem:", ex);
                result.ResultException = BaseExceptionEnum.FileReNameException;
            }
            return result;
        }

        public FolderReNameResult ChangeFolderNameService(FolderReNameArgs folderReNameArgs)
        {
            var result = new FolderReNameResult();
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(folderReNameArgs.UserId));
                    var current_folder = repository.GetSingle<FileDbModel>(x => x.ISFILE==false&&x.FILESID.Equals(folderReNameArgs.FolderSid));
                    if (current_folder != null)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_folder.OWNERID));
                        var folderPath = current_comapny.SHORTNAME + current_folder.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_folder.FILEPATH))
                            folderPath += (@"\" + current_folder.FILENAME);
                        var logPath = folderPath; //+ @"\" + current_file.FILENAME;
                        var targetPath = folderPath.Replace(current_folder.FILENAME, folderReNameArgs.FolderNewName);
                        var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath); //+ "/" + current_file.FILENAME;
                        var newFilePath = filePath.TrimEnd(current_folder.FILENAME.ToArray())+folderReNameArgs.FolderNewName;

                        if (Directory.Exists(filePath))
                        {
                            var directory = new DirectoryInfo(filePath);
                            directory.MoveTo(newFilePath);
                            var oldPath = current_folder.FILEPATH;
                            if (string.IsNullOrEmpty(oldPath))
                                oldPath = "/" + current_folder.FILENAME;
                            current_folder.FILEPATH =
                                current_folder.FILEPATH.TrimEnd(current_folder.FILENAME.ToArray()) +
                                folderReNameArgs.FolderNewName;
                            current_folder.FILENAME = folderReNameArgs.FolderNewName;
                            current_folder.UPDATER = current_user.NAME;
                            current_folder.UPDATERID = current_user.SID;
                            current_folder.UPDATETIME = DateTime.Now;
                            current_folder.Update();
                            var folderCollection = repository.GetAll<FileDbModel>(x => x.FILEPATH.StartsWith(oldPath));
                            foreach (var fileDbModel in folderCollection)
                            {
                                fileDbModel.FILEPATH = fileDbModel.FILEPATH.Replace(oldPath, current_folder.FILEPATH);
                                fileDbModel.Update();
                            }
                            var fileLogModel = new FileLogDbModel
                            {
                                LOGSID = Guid.NewGuid().ToString(),
                                LOG = string.Format("修改文件夹名称: {0} 成功!", logPath),
                                LOGTIME = DateTime.Now,
                                LOGTYPE = "重命名",
                                OBJECTID = folderReNameArgs.FolderSid,
                                TARGETNAME = targetPath,
                                USERID = current_user.SID,
                                USERNAME = current_user.NAME
                            };
                            fileLogModel.Create();
                            result.Result = true;
                        }
                        else
                            result.ResultException = BaseExceptionEnum.NotFindFileException;
                    }
                    else
                        result.ResultException = BaseExceptionEnum.NotFindFileException;
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("ChangeFolderNameService has problem:", ex);
                result.ResultException = BaseExceptionEnum.FolderReNameException;
            }
            return result;
        }

        public FolderDeleteResult DeleteFolderService(FolderDeleteArgs folderDeleteArgs)
        {
            var result = new FolderDeleteResult();
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(folderDeleteArgs.UserId));
                    var current_folder = repository.GetSingle<FileDbModel>(x => x.ISFILE == false && x.FILESID.Equals(folderDeleteArgs.FolderSid));
                    if (current_folder != null)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_folder.OWNERID));
                        // kill target file, if already exists
                        var folderPath = current_comapny.SHORTNAME + current_folder.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_folder.FILEPATH))
                            folderPath += (@"\" + current_folder.FILENAME);
                        var logPath = folderPath; //+ @"\" + current_file.FILENAME;
                        var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath);
                        if(Directory.Exists(filePath))
                        {
                            Directory.Delete(filePath,true);
                            var folderAndFileCollection =
                                repository.GetAll<FileDbModel>(x => x.FILEPATH.StartsWith(current_folder.FILEPATH));
                            var fileSidCollection = folderAndFileCollection.Select(x => x.FILESID).ToList();
                            fileSidCollection.Add(current_folder.FILESID);
                            var folderAndFileRoeCollection =
                                repository.GetAll<FileRoleDbModel>(x => fileSidCollection.Contains(x.FILESID));
                            //Delete file and folder role
                            foreach (var fileRoleDbModel in folderAndFileRoeCollection)
                                fileRoleDbModel.Delete();
                            //Delete file and foler
                            foreach (var filedbModel in folderAndFileCollection)
                                filedbModel.Delete();
                            var fileLogModel = new FileLogDbModel
                            {
                                LOGSID = Guid.NewGuid().ToString(),
                                LOG = string.Format("删除文件夹: {0} 成功!", logPath),
                                LOGTIME = DateTime.Now,
                                LOGTYPE = "删除",
                                OBJECTID = current_folder.FILESID,
                                TARGETNAME = logPath,
                                USERID = current_user.SID,
                                USERNAME = current_user.NAME
                            };
                            fileLogModel.Create();
                            current_folder.Delete();
                            result.Result = true;
                        }
                        else
                            result.ResultException = BaseExceptionEnum.DeleteFileNotFileException;
                    }
                    else
                        result.ResultException = BaseExceptionEnum.DeleteFileNotFileException;
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("DeleteFolderService has problem:", ex);
                result.ResultException = BaseExceptionEnum.DeleteFolderException;
            }
            return result;
        }

        public FileCopyToResult CopyFileToOtherFolder(FileCopyToArgs fileCopyToArgs)
        {
            var result = new FileCopyToResult();
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(fileCopyToArgs.UserId));
                    var current_file = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(fileCopyToArgs.FileSid));
                    if (current_file != null)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_file.OWNERID));
                        var folderPath = current_comapny.SHORTNAME + current_file.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_file.FILEPATH))
                            folderPath += (@"\" + current_file.FILENAME);
                        var logPath = folderPath + @"\" + current_file.FILENAME;
                        var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath) + @"\" + current_file.FILENAME;
                        if (File.Exists(filePath))
                        {
                            foreach (var targetFolderSid in fileCopyToArgs.TargetFolderSid)
                            {
                                var target_folder = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(targetFolderSid));
                                var hasFileTarget =
                                    repository.GetSingle<FileDbModel>(x => x.PARENTID.Equals(target_folder.FILESID)
                                                                           && x.ISFILE &&
                                                                           x.FILENAME.Equals(current_file.FILENAME));
                                if(null != hasFileTarget) continue;
                                var target_company = repository.GetSingle<Company>(x => x.SID.Equals(target_folder.OWNERID));
                                var targetPath = target_company.SHORTNAME + target_folder.FILEPATH;
                                targetPath = targetPath.Replace("/", @"\");
                                if (string.IsNullOrEmpty(target_folder.FILEPATH))
                                    targetPath += (@"\" + target_folder.FILENAME);
                                var targelogtPath = targetPath + @"\" + current_file.FILENAME;
                                var targetFolderPath = Path.Combine(GlobalString.System_Config_String.FileDiskPath,
                                                                    targetPath);
                                var newFilePath = targetFolderPath + @"\" + current_file.FILENAME;
                                if(!Directory.Exists(targetFolderPath)) continue;
                                var fileInfo = new FileInfo(filePath);
                                fileInfo.CopyTo(newFilePath);
                                current_file.FILENAME = current_file.FILENAME;
                                current_file.UPDATER = current_user.NAME;
                                current_file.UPDATERID = current_user.SID;
                                current_file.UPDATETIME = DateTime.Now;
                                current_file.Update();
                                var newFileModel = new FileDbModel
                                {
                                    CREATETIME = DateTime.Now,
                                    CREATOR = current_user.NAME,
                                    CREATORID = current_user.SID,
                                    FILEDESCRIBE = current_file.FILEDESCRIBE,
                                    FILEMARK = current_file.FILEMARK,
                                    FILENAME = current_file.FILENAME,
                                    FILEPATH = target_folder.FILEPATH,
                                    FILESIZE = current_file.FILESIZE,
                                    FILESID = Guid.NewGuid().ToString(),
                                    FILESORT = current_file.FILESORT,
                                    FILETYPE = current_file.FILETYPE,
                                    ISFILE = current_file.ISFILE,
                                    ISSHARE = current_file.ISSHARE,
                                    OWNERID = target_folder.OWNERID,
                                    PARENTID = target_folder.FILESID,
                                    UPDATER = current_user.NAME,
                                    UPDATERID = current_user.SID,
                                    UPDATETIME = DateTime.Now
                                };
                                newFileModel.Create();
                                var folderRole =
                                    repository.GetAll<FileRoleDbModel>(x => x.FILESID.Equals(target_folder.FILESID));
                                foreach (var newFileRole in folderRole.Select(fileRoleDbModel => new FileRoleDbModel
                                {
                                    FILESID = newFileModel.FILESID,
                                    FLAGSID = fileRoleDbModel.FLAGSID,
                                    INHERITFILESID = target_folder.FILESID,
                                    ISALLOWALLOCATE = true,
                                    ISINHERIT = true,
                                    ISCREATE = fileRoleDbModel.ISCREATE,
                                    ISDELETE = fileRoleDbModel.ISDELETE,
                                    ISOWNER = fileRoleDbModel.ISOWNER,
                                    ISREAD = fileRoleDbModel.ISREAD,
                                    ISUPDATE = fileRoleDbModel.ISUPDATE,
                                    RELATIONID = fileRoleDbModel.RELATIONID,
                                    ROLESID = Guid.NewGuid().ToString(),
                                    ROLETYPE = fileRoleDbModel.ROLETYPE,
                                    SETUSERID = fileRoleDbModel.SETUSERID,
                                    SETUSERNAME = fileRoleDbModel.SETUSERNAME
                                }))
                                {
                                    newFileRole.Create();
                                }
                                var fileLogModel = new FileLogDbModel
                                {
                                    LOGSID = Guid.NewGuid().ToString(),
                                    LOG = string.Format("复制文件: {0} 成功!", logPath),
                                    LOGTIME = DateTime.Now,
                                    LOGTYPE = "复制文件",
                                    OBJECTID = current_file.FILESID,
                                    TARGETNAME = targelogtPath,
                                    USERID = current_user.SID,
                                    USERNAME = current_user.NAME
                                };
                                fileLogModel.Create();
                                result.Result = true;
                            }
                        }
                        else
                            result.ResultException = BaseExceptionEnum.NotFindFileException;
                    }
                    else
                        result.ResultException = BaseExceptionEnum.NotFindFileException;
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CopyFileToOtherFolder has problem:", ex);
                result.ResultException = BaseExceptionEnum.CopyFileException;
            }
            return result;
        }

        public FileCutToResult CutFileToOtherFolder(FileCutToArgs fileCutToArgs)
        {
            var result = new FileCutToResult();
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(fileCutToArgs.UserId));
                    var current_file = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(fileCutToArgs.FileSid));
                    if (current_file != null)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_file.OWNERID));
                        var target_folder = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(fileCutToArgs.TargetFolderSid));
                        var target_company = repository.GetSingle<Company>(x => x.SID.Equals(target_folder.OWNERID));

                        var folderPath = current_comapny.SHORTNAME + current_file.FILEPATH;
                        var targetPath = target_company.SHORTNAME + target_folder.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        targetPath = targetPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_file.FILEPATH))
                            folderPath += (@"\" + current_file.FILENAME);
                        if (string.IsNullOrEmpty(target_folder.FILEPATH))
                            targetPath += (@"\" + target_folder.FILENAME);

                        var logPath = folderPath + @"\" + current_file.FILENAME;
                        var targelogtPath = targetPath + @"\" + current_file.FILENAME;
                        var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath) + @"\" + current_file.FILENAME;
                        var newFolderPath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, targetPath);
                        var newFilePath = newFolderPath + @"\" + current_file.FILENAME;
                        if (CheckUploadingFile(filePath))
                        {
                            result.ResultException = BaseExceptionEnum.FileUploading;
                            return result;
                        }
                        if (File.Exists(filePath) && Directory.Exists(newFolderPath))
                        {
                            var fileInfo = new FileInfo(filePath);
                            fileInfo.MoveTo(newFilePath);
                            current_file.FILENAME = current_file.FILENAME;
                            current_file.UPDATER = current_user.NAME;
                            current_file.UPDATERID = current_user.SID;
                            current_file.UPDATETIME = DateTime.Now;
                            current_file.PARENTID = target_folder.FILESID;
                            current_file.FILEPATH = target_folder.FILEPATH;
                            current_file.OWNERID = target_folder.OWNERID;
                            current_file.Update();
                            var fileRole =
                                repository.GetAll<FileRoleDbModel>(x => x.FILESID.Equals(current_file.FILESID));
                            foreach (var fileRoleDbModel in fileRole)
                                fileRoleDbModel.Delete();
                            var folderRole =
                        repository.GetAll<FileRoleDbModel>(x => x.FILESID.Equals(target_folder.FILESID));
                            foreach (var newFileRole in folderRole.Select(fileRoleDbModel => new FileRoleDbModel
                            {
                                FILESID = current_file.FILESID,
                                FLAGSID = fileRoleDbModel.FLAGSID,
                                INHERITFILESID = target_folder.FILESID,
                                ISALLOWALLOCATE = true,
                                ISINHERIT = true,
                                ISCREATE = fileRoleDbModel.ISCREATE,
                                ISDELETE = fileRoleDbModel.ISDELETE,
                                ISOWNER = fileRoleDbModel.ISOWNER,
                                ISREAD = fileRoleDbModel.ISREAD,
                                ISUPDATE = fileRoleDbModel.ISUPDATE,
                                RELATIONID = fileRoleDbModel.RELATIONID,
                                ROLESID = Guid.NewGuid().ToString(),
                                ROLETYPE = fileRoleDbModel.ROLETYPE,
                                SETUSERID = fileRoleDbModel.SETUSERID,
                                SETUSERNAME = fileRoleDbModel.SETUSERNAME
                            }))
                            {
                                newFileRole.Create();
                            }
                            var fileLogModel = new FileLogDbModel
                            {
                                LOGSID = Guid.NewGuid().ToString(),
                                LOG = string.Format("剪切文件: {0} 成功!", logPath),
                                LOGTIME = DateTime.Now,
                                LOGTYPE = "剪切文件",
                                OBJECTID = current_file.FILESID,
                                TARGETNAME = targelogtPath,
                                USERID = current_user.SID,
                                USERNAME = current_user.NAME
                            };
                            fileLogModel.Create();
                            result.Result = true;
                        }
                        else
                            result.ResultException = BaseExceptionEnum.NotFindFileException;
                    }
                    else
                        result.ResultException = BaseExceptionEnum.NotFindFileException;
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CutFileToOtherFolder has problem:", ex);
                result.ResultException = BaseExceptionEnum.CutFileException;
            }
            return result;
        }

        public FolderCopyToResult CopyFolderToOtherFolder(FolderCopyToArgs folderCopyToArgs)
        {
            var result = new FolderCopyToResult();
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(folderCopyToArgs.UserId));
                    var current_folder = repository.GetSingle<FileDbModel>(x => x.ISFILE == false && x.FILESID.Equals(folderCopyToArgs.FolderSid));
                    if (current_folder != null)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_folder.OWNERID));
                        var folderPath = current_comapny.SHORTNAME + current_folder.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_folder.FILEPATH))
                            folderPath += (@"\" + current_folder.FILENAME);
                        var logPath = folderPath; //+ @"\" + current_file.FILENAME;
                        folderPath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath); //+ "/" + current_file.FILENAME;
                        if (Directory.Exists(folderPath))
                        {
                            foreach (var targetFolderSid in folderCopyToArgs.TargetFolderSid)
                            {
                                var target_folder =
                                    repository.GetSingle<FileDbModel>(
                                        x => x.FILESID.Equals(targetFolderSid));
                                var hasSubFolderName =
                                    repository.GetSingle<FileDbModel>(
                                        x =>
                                        x.PARENTID.Equals(target_folder.FILESID) &&
                                        x.FILENAME.Equals(current_folder.FILENAME));
                                if(null != hasSubFolderName) continue;
                                var target_company =
                                    repository.GetSingle<Company>(x => x.SID.Equals(target_folder.OWNERID));
                                var newFolderPath = target_company.SHORTNAME + target_folder.FILEPATH;
                                newFolderPath = newFolderPath.Replace("/", @"\");
                                if (string.IsNullOrEmpty(target_folder.FILEPATH))
                                    newFolderPath += (@"\" + target_folder.FILENAME);
                                var targetPath = newFolderPath;
                                newFolderPath = Path.Combine(GlobalString.System_Config_String.FileDiskPath,
                                                             newFolderPath);
                                if (!Directory.Exists(newFolderPath)) continue;
                                newFolderPath = newFolderPath + @"\" + current_folder.FILENAME;
                                var copyfolderResult = CopyFolder(folderPath, newFolderPath);
                                if (copyfolderResult)
                                {
                                    var newFileModel = new FileDbModel
                                                           {
                                                               CREATETIME = DateTime.Now,
                                                               CREATOR = current_user.NAME,
                                                               CREATORID = current_user.SID,
                                                               FILEDESCRIBE = current_folder.FILEDESCRIBE,
                                                               FILEMARK = current_folder.FILEMARK,
                                                               FILENAME = current_folder.FILENAME,
                                                               FILEPATH =
                                                                   target_folder.FILEPATH + "/" +
                                                                   current_folder.FILENAME,
                                                               FILESIZE = current_folder.FILESIZE,
                                                               FILESID = Guid.NewGuid().ToString(),
                                                               FILESORT = current_folder.FILESORT,
                                                               FILETYPE = current_folder.FILETYPE,
                                                               ISFILE = current_folder.ISFILE,
                                                               ISSHARE = current_folder.ISSHARE,
                                                               OWNERID = target_folder.OWNERID,
                                                               PARENTID = target_folder.FILESID,
                                                               UPDATER = current_user.NAME,
                                                               UPDATERID = current_user.SID,
                                                               UPDATETIME = DateTime.Now
                                                           };
                                    newFileModel.Create();
                                    var oldPath = current_folder.FILEPATH;
                                    var folderCollection =
                                        repository.GetAll<FileDbModel>(x => x.FILEPATH.StartsWith(oldPath) && !x.FILESID.Equals(current_folder.FILESID)).ToList();
                                    var newSubFiles = folderCollection.Select(fileDbModel => new FileDbModel
                                                                                                 {
                                                                                                     PARENTID = fileDbModel.PARENTID,
                                                                                                     CREATETIME =
                                                                                                         DateTime.Now,
                                                                                                     CREATOR =
                                                                                                         current_user.
                                                                                                         NAME,
                                                                                                     CREATORID =
                                                                                                         current_user.
                                                                                                         SID,
                                                                                                     FILEDESCRIBE =
                                                                                                         fileDbModel.
                                                                                                         FILEDESCRIBE,
                                                                                                     FILEMARK =
                                                                                                         fileDbModel.
                                                                                                         FILEMARK,
                                                                                                     FILENAME =
                                                                                                         fileDbModel.
                                                                                                         FILENAME,
                                                                                                     FILEPATH =
                                                                                                         fileDbModel.
                                                                                                         FILEPATH.
                                                                                                         Replace(
                                                                                                             oldPath,
                                                                                                             newFileModel
                                                                                                                 .
                                                                                                                 FILEPATH),
                                                                                                     FILESIZE =
                                                                                                         fileDbModel.
                                                                                                         FILESIZE,
                                                                                                     FILESORT =
                                                                                                         fileDbModel.
                                                                                                         FILESORT,
                                                                                                     FILETYPE =
                                                                                                         fileDbModel.
                                                                                                         FILETYPE,
                                                                                                     ISFILE =
                                                                                                         fileDbModel.
                                                                                                         ISFILE,
                                                                                                     ISSHARE =
                                                                                                         fileDbModel.
                                                                                                         ISSHARE,
                                                                                                     OWNERID =
                                                                                                         newFileModel.
                                                                                                         OWNERID,
                                                                                                     UPDATER =
                                                                                                         current_user.
                                                                                                         NAME,
                                                                                                     UPDATERID =
                                                                                                         current_user.
                                                                                                         SID,
                                                                                                     UPDATETIME =
                                                                                                         DateTime.Now
                                                                                                 }).ToList();
                                    if (newSubFiles.Count > 0)
                                    {
                                        var oldSubAllFolder =
                                            newSubFiles.Where(x => x.PARENTID.Equals(current_folder.FILESID)).ToList();
                                        foreach (var fileDbModel in oldSubAllFolder)
                                            fileDbModel.PARENTID = newFileModel.FILESID;
                                        var fileSidCollection = newSubFiles.Select(x => x.FILESID).ToList();
                                        var parentSidCollection = newSubFiles.Select(x => x.PARENTID).ToList();
                                        fileSidCollection.AddRange(parentSidCollection);
                                        fileSidCollection = fileSidCollection.Distinct().ToList();
                                        fileSidCollection.Remove(newFileModel.FILESID);
                                        foreach (var oldId in fileSidCollection)
                                        {
                                            var newId = Guid.NewGuid().ToString();
                                            var newSubItem =
                                                newSubFiles.Where(
                                                    x => x.FILESID.Equals(oldId) || x.PARENTID.Equals(oldId));
                                            foreach (var fileDbModel in newSubItem)
                                            {
                                                if (fileDbModel.FILESID.Equals(oldId))
                                                    fileDbModel.FILESID = newId;
                                                if (fileDbModel.PARENTID.Equals(oldId))
                                                    fileDbModel.PARENTID = newId;
                                            }
                                        }
                                        foreach (var filedbModel in newSubFiles)
                                            filedbModel.Create();
                                    }

                                    var fileLogModel = new FileLogDbModel
                                                           {
                                                               LOGSID = Guid.NewGuid().ToString(),
                                                               LOG = string.Format("复制文件夹: {0} 成功!", logPath),
                                                               LOGTIME = DateTime.Now,
                                                               LOGTYPE = "复制文件夹",
                                                               OBJECTID = folderCopyToArgs.FolderSid,
                                                               TARGETNAME = targetPath,
                                                               USERID = current_user.SID,
                                                               USERNAME = current_user.NAME
                                                           };
                                    fileLogModel.Create();
                                    result.Result = true;
                                }
                            }
                        }
                        else
                            result.ResultException = BaseExceptionEnum.NotFindFileException;
                    }
                    else
                        result.ResultException = BaseExceptionEnum.NotFindFileException;
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CopyFolderToOtherFolder has problem:", ex);
                result.ResultException = BaseExceptionEnum.CopyFolderException;
            }
            return result;
        }

        public FolderCutToResult CutFolderToOtherFolder(FolderCutToArgs folderCutToArgs)
        {
            var result = new FolderCutToResult();
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(folderCutToArgs.UserId));
                    var current_folder = repository.GetSingle<FileDbModel>(x => x.ISFILE == false && x.FILESID.Equals(folderCutToArgs.FolderSid));
                    if (current_folder != null)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_folder.OWNERID));
                        var target_folder = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(folderCutToArgs.TargetFolderSid));
                        var target_company = repository.GetSingle<Company>(x => x.SID.Equals(target_folder.OWNERID));

                        var folderPath = current_comapny.SHORTNAME + current_folder.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        var newFolderPath = target_company.SHORTNAME + target_folder.FILEPATH;
                        newFolderPath = newFolderPath.Replace("/", @"\");

                        if (string.IsNullOrEmpty(current_folder.FILEPATH))
                            folderPath += (@"\" + current_folder.FILENAME);
                        if (string.IsNullOrEmpty(target_folder.FILEPATH))
                            newFolderPath += (@"\" + target_folder.FILENAME);

                        var logPath = folderPath; //+ @"\" + current_file.FILENAME;
                        var targetPath = newFolderPath;
                        folderPath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath); //+ "/" + current_file.FILENAME;
                        newFolderPath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, newFolderPath);

                        if (Directory.Exists(folderPath) && Directory.Exists(newFolderPath))
                        {
                            newFolderPath = newFolderPath + @"\" + current_folder.FILENAME;
                            var copyfolderResult = CopyFolder(folderPath, newFolderPath);
                            if (copyfolderResult)
                            {
                                Directory.Delete(folderPath,true);
                                var oldPath = current_folder.FILEPATH;
                                current_folder.PARENTID = target_folder.FILESID;
                                current_folder.FILEPATH = target_folder.FILEPATH + "/" + current_folder.FILENAME;
                                current_folder.UPDATER = current_user.NAME;
                                current_folder.UPDATERID = current_user.SID;
                                current_folder.UPDATETIME = DateTime.Now;
                                current_folder.OWNERID = target_folder.OWNERID;
                                current_folder.Update();
                                var folderCollection = repository.GetAll<FileDbModel>(x => x.FILEPATH.StartsWith(oldPath));
                                foreach (var fileDbModel in folderCollection)
                                {
                                    fileDbModel.OWNERID = current_folder.OWNERID;
                                    fileDbModel.FILEPATH = fileDbModel.FILEPATH.Replace(oldPath, current_folder.FILEPATH);
                                    fileDbModel.Update();
                                }
                                var folderSid = folderCollection.Select(x => x.FILESID).ToList();
                                var fileRoleDelete =
                                    repository.GetAll<FileRoleDbModel>(x => folderSid.Contains(x.FILESID)).ToList();
                                foreach (var fileRoleDbModel in fileRoleDelete)
                                    fileRoleDbModel.Delete();

                                var fileLogModel = new FileLogDbModel
                                {
                                    LOGSID = Guid.NewGuid().ToString(),
                                    LOG = string.Format("剪切文件夹: {0} 成功!", logPath),
                                    LOGTIME = DateTime.Now,
                                    LOGTYPE = "剪切文件夹",
                                    OBJECTID = current_folder.FILESID,
                                    TARGETNAME = targetPath,
                                    USERID = current_user.SID,
                                    USERNAME = current_user.NAME
                                };
                                fileLogModel.Create();
                                result.Result = true;
                            }
                            else
                                result.ResultException = BaseExceptionEnum.CopyFolderException;
                        }
                        else
                            result.ResultException = BaseExceptionEnum.NotFindFileException;
                    }
                    else
                        result.ResultException = BaseExceptionEnum.NotFindFileException;
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CutFolderToOtherFolder has problem:", ex);
                result.ResultException = BaseExceptionEnum.CutFolderException;
            }
            return result;
        }

        public NewFolderResult CreateNewFolder(NewFolderArgs newFolderArgs)
        {
            var result = new NewFolderResult();
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(newFolderArgs.UserId));
                    var parent_folder = repository.GetSingle<FileDbModel>(x => x.ISFILE == false && x.FILESID.Equals(newFolderArgs.ParentFolderSid));
                    //var current_folder = repository.GetSingle<FileDbModel>(x => x.ISFILE == false && x.FILESID.Equals(folderCutToArgs.FolderSid));
                    var newfolder_path = string.Empty;
                    var newfolder_dataPath = string.Empty;
                    var parentId = string.Empty;
                    var ownerId = string.Empty;
                    if(parent_folder == null)
                    {
                        parentId = "0";
                        newfolder_dataPath = "/" + newFolderArgs.NewFolderName;
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(newFolderArgs.ParentFolderSid));
                        newfolder_path = current_comapny.SHORTNAME + @"\" + newFolderArgs.NewFolderName;
                        newfolder_path = Path.Combine(GlobalString.System_Config_String.FileDiskPath, newfolder_path);
                        ownerId = newFolderArgs.ParentFolderSid;
                    }
                    else
                    {
                        parentId = parent_folder.FILESID;
                        if (string.IsNullOrEmpty(parent_folder.FILEPATH))
                            newfolder_dataPath = "/"+parent_folder.FILENAME+ "/" + newFolderArgs.NewFolderName;
                    else
                            newfolder_dataPath = parent_folder.FILEPATH + "/" + newFolderArgs.NewFolderName;
                        var folder_comapny = repository.GetSingle<Company>(x => x.SID.Equals(parent_folder.OWNERID));
                        if (string.IsNullOrEmpty(parent_folder.FILEPATH))
                            newfolder_path = folder_comapny.SHORTNAME + @"\" + parent_folder.FILENAME + @"\" + newFolderArgs.NewFolderName;
                        else
                            newfolder_path = folder_comapny.SHORTNAME  + parent_folder.FILEPATH + @"\" + newFolderArgs.NewFolderName;
                        newfolder_path = newfolder_path.Replace("/", @"\");
                        newfolder_path = Path.Combine(GlobalString.System_Config_String.FileDiskPath, newfolder_path);
                        ownerId = parent_folder.OWNERID;
                    }
                    if (Directory.Exists(newfolder_path))
                        result.ResultException = BaseExceptionEnum.CreateFolderHaveFolderExpcetion;
                    else
                    {
                        Directory.CreateDirectory(newfolder_path);
                        var folderInfo = new FileDbModel
                                             {
                                                 FILESID =  Guid.NewGuid().ToString(),
                                                 FILENAME = newFolderArgs.NewFolderName,
                                                 PARENTID = parentId,
                                                 FILEPATH = newfolder_dataPath,
                                                 FILETYPE = false,
                                                 OWNERID = ownerId,
                                                 ISFILE = false,
                                                 CREATOR = current_user.NAME,
                                                 CREATORID = current_user.SID,
                                                 CREATETIME = DateTime.Now,
                                                 UPDATER = current_user.NAME,
                                                 UPDATERID = current_user.SID,
                                                 UPDATETIME = DateTime.Now,
                                                 FILESORT = 0,
                                                 FILESIZE = 0
                                             };
                        folderInfo.Create();
                        if(null != parent_folder)
                        {
                            var folderRole =
                                repository.GetAll<FileRoleDbModel>(x => x.FILESID.Equals(parent_folder.FILESID));
                            foreach (var newFileRole in folderRole.Select(fileRoleDbModel => new FileRoleDbModel
                            {
                                FILESID = folderInfo.FILESID,
                                FLAGSID = fileRoleDbModel.FLAGSID,
                                INHERITFILESID = parent_folder.FILESID,
                                ISALLOWALLOCATE = true,
                                ISINHERIT = true,
                                ISCREATE = fileRoleDbModel.ISCREATE,
                                ISDELETE = fileRoleDbModel.ISDELETE,
                                ISOWNER = fileRoleDbModel.ISOWNER,
                                ISREAD = fileRoleDbModel.ISREAD,
                                ISUPDATE = fileRoleDbModel.ISUPDATE,
                                RELATIONID = fileRoleDbModel.RELATIONID,
                                ROLESID = Guid.NewGuid().ToString(),
                                ROLETYPE = fileRoleDbModel.ROLETYPE,
                                SETUSERID = fileRoleDbModel.SETUSERID,
                                SETUSERNAME = fileRoleDbModel.SETUSERNAME
                            }))
                            {
                                newFileRole.Create();
                            }
                        }
                        var fileLogModel = new FileLogDbModel
                        {
                            LOGSID = Guid.NewGuid().ToString(),
                            LOG = string.Format("成功新建了文件夹: {0}", newfolder_dataPath),
                            LOGTIME = DateTime.Now,
                            LOGTYPE = "新建文件夹",
                            OBJECTID = folderInfo.FILESID,
                            TARGETNAME = newfolder_dataPath,
                            USERID = current_user.SID,
                            USERNAME = current_user.NAME
                        };
                        fileLogModel.Create();
                        result.Result = true;
                        result.NewFolderSid = folderInfo.FILESID;
                    }
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CreateNewFolder has problem:", ex);
                result.ResultException = BaseExceptionEnum.CreateFolderException;
            }
            return result;
        }

        /// <summary>
        /// Copy文件夹
        /// </summary>
        public bool CopyFolder(string sPath, string dPath)
        {
            try
            {
                // 创建目的文件夹
                if (!Directory.Exists(dPath))
                    Directory.CreateDirectory(dPath);
                // 拷贝文件
                var sDir = new DirectoryInfo(sPath);
                var fileArray = sDir.GetFiles();
                foreach (var file in fileArray)
                    file.CopyTo(dPath + "\\" + file.Name, true);
                // 循环子文件夹
                var dDir = new DirectoryInfo(dPath);
                var subDirArray = sDir.GetDirectories();
                foreach (var subDir in subDirArray)
                {
                    CopyFolder(subDir.FullName, dPath + "//" + subDir.Name);
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        #region SetCache
        private List<CompanyGroupResult> cacheCompanyGroup;
        private List<UserGroupResult> cacheUserGroup;
        private List<CompanyResult> cacheCompany;
        private void SetCache()
        {
            using (var repository = new Repository())
            {
                var queryCompanyGroup = repository.GetAll<CompanyGroup>();
                var cacheCompanyGroup =
                    Mapper.Map<IList<CompanyGroup>, List<CompanyGroupResult>>(queryCompanyGroup);
                CacheGlobal.Add(GlobalString.System_Config_String.CacheCompanyGroupCollection, cacheCompanyGroup);
                var queryUserGroup = repository.GetAll<UserGroup>();
                var cacheUserGroup =
                  Mapper.Map<IList<UserGroup>, List<UserGroupResult>>(queryUserGroup);
                CacheGlobal.Add(GlobalString.System_Config_String.CacheUserGroupCollection, cacheUserGroup);
                var queryComapny = from a in ActiveRecordLinq.AsQueryable<Company>()
                                   where !(from b in ActiveRecordLinq.AsQueryable<Company>()
                                           where b.ORDERNUMBER.StartsWith("DY")
                                           select b.ID).Contains(a.ID)
                                   select new CompanyResult
                                   {
                                       CompanyName = a.NAME ?? "",
                                       Id = a.ID ?? "",
                                       Pid = a.PID ?? "",
                                       ShortName = a.SHORTNAME ?? "",
                                       Sncode = a.SNCODE ?? ""
                                   };
                var cacheCompany = queryComapny.ToList();
                CacheGlobal.Add(GlobalString.System_Config_String.CacheCompanyCollection, cacheCompany);
            }
        }
        private void CheckCache()
        {
            cacheCompanyGroup =
         CacheGlobal.GetCache(GlobalString.System_Config_String.CacheCompanyGroupCollection) as
         List<CompanyGroupResult>;
            cacheUserGroup =
                CacheGlobal.GetCache(GlobalString.System_Config_String.CacheUserGroupCollection) as
                List<UserGroupResult>;
            cacheCompany =
                CacheGlobal.GetCache(GlobalString.System_Config_String.CacheCompanyCollection) as
                List<CompanyResult>;
            if (null != cacheCompany) return;
            SetCache();
            cacheCompanyGroup =
                CacheGlobal.GetCache(GlobalString.System_Config_String.CacheCompanyGroupCollection) as
                List<CompanyGroupResult>;
            cacheUserGroup =
                CacheGlobal.GetCache(GlobalString.System_Config_String.CacheUserGroupCollection) as
                List<UserGroupResult>;
            cacheCompany =
                CacheGlobal.GetCache(GlobalString.System_Config_String.CacheCompanyCollection) as
                List<CompanyResult>;
        }
        #endregion

        public FileRoleAddResultCollection GetFolderRole(FileRoleAddArgs fileRoleAddArgs)
        {
            var result = new FileRoleAddResultCollection();
            try
            {
                CheckCache();
                using (var repository = new Repository())
                {
                    var fileRoleCollection =
                        repository.GetAll<FileRoleDbModel>(x => x.FILESID.Equals(fileRoleAddArgs.FileSid));
                    result.Result = Mapper.Map<IList<FileRoleDbModel>, List<FileRoleAddResult>>(fileRoleCollection);
                    var parentCollection = fileRoleCollection.Select(x => x.INHERITFILESID).ToList();
                    var userCollectionDb =
                        fileRoleCollection.Where(x => x.ROLETYPE.Equals("0")).Select(x => x.RELATIONID).ToList();
                    var fileDbMeol = new List<FileDbModel>();
                    var userCollection = new List<UserDbModel>();
                    if(parentCollection.Any())
                        fileDbMeol = repository.GetAll<FileDbModel>(x => parentCollection.Contains(x.FILESID)).ToList();
                    if(userCollectionDb.Any())
                        userCollection = repository.GetAll<UserDbModel>(x => userCollectionDb.Contains(x.SID)).ToList();
                    var deleteObj =
                        result.Result.Where(
                            x => (x.RoleType.Equals("2") || x.RoleType.Equals("3")) && x.RelationId.Equals("-1")).ToList();
                    //foreach (var fileRoleAddResult in deleteObj)
                    //    result.Result.Remove(fileRoleAddResult);
                    foreach (var t in deleteObj)
                        result.Result.Remove(t);
                    foreach (var fileRoleModel in result.Result)
                    {
                        switch (fileRoleModel.RoleType)
                        {
                                //用户
                            case "0":
                                fileRoleModel.RelationName =
                                    userCollection.FirstOrDefault(x => x.USERID.Equals(fileRoleModel.RelationId)).NAME;
                                break;
                                //组织机构
                            case "1":
                                fileRoleModel.RelationName =
                                    cacheCompany.FirstOrDefault(x => x.Id.Equals(fileRoleModel.RelationId)).ShortName;
                                break;
                                //人员公共组
                            case "2":
                                var userGroup =
                                    cacheUserGroup.FirstOrDefault(x => !string.IsNullOrEmpty(x.Sid)&&x.Sid.Equals(fileRoleModel.RelationId));
                                fileRoleModel.RelationName = userGroup.Name;
                                break;
                                //组织机构公共组
                            case "3":
                                var company =
                                    cacheCompanyGroup.FirstOrDefault(x => x.Sid.Equals(fileRoleModel.RelationId));
                                fileRoleModel.RelationName = company.Name;
                                break;
                                //任何人
                            case "5":
                                fileRoleModel.RelationName = "AnyOne";
                                break;
                        }
                        if (fileRoleModel.IsInherit)
                            fileRoleModel.InheritFileName =
                                fileDbMeol.FirstOrDefault(x => x.FILESID.Equals(fileRoleModel.InheritFileSId)).FILENAME;
                    }
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("GetFolderRole has problem:", ex);
                result.ResultException = BaseExceptionEnum.GetFolderRoleException;
            }
            return result;
        }

        public NewFileRoleResultCollection NewFileRole(NewFileRoleCollectionArgs newFileRoleCollectionArgs)
        {
            var result = new NewFileRoleResultCollection();
            try
            {
                foreach (var userGroupResult in newFileRoleCollectionArgs.NewFileRoleCollection)
                {
                    userGroupResult.RoleSid = Guid.NewGuid().ToString();
                    userGroupResult.FlagSid = Guid.NewGuid().ToString();
                }
                var newRoleCollection = Mapper.Map<List<FileRoleAddResult>,List<FileRoleDbModel>> (newFileRoleCollectionArgs.NewFileRoleCollection);
                foreach (var fileRoleDbModel in newRoleCollection)
                {
                    fileRoleDbModel.Create();
                }
                result.Result = Mapper.Map<List<FileRoleDbModel>, List<NewFileRoleResult>>(newRoleCollection);
                var fileLogModel = new FileLogDbModel
                {
                    LOGSID = Guid.NewGuid().ToString(),
                    LOG = string.Format("添加权限:  成功!"),
                    LOGTIME = DateTime.Now,
                    LOGTYPE = "添加权限",
                    OBJECTID = newFileRoleCollectionArgs.NewFileRoleCollection[0].FileSid,
                    TARGETNAME = "添加新的权限!",
                    USERID = newFileRoleCollectionArgs.NewFileRoleCollection[0].SetUserId,
                    USERNAME = newFileRoleCollectionArgs.NewFileRoleCollection[0].SetUserName
                };
                fileLogModel.Create();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("NewFileRole has problem:", ex);
                result.ResultException = BaseExceptionEnum.NewFileRoleException;
            }
            return result;
        }

        public FileRoleChangeResult ChangeFileRole(FileRoleChangeArgs fileRoleChangeArgs)
        {
            var result = new FileRoleChangeResult();
            try
            {
                using (var repository = new Repository())
                {
                    var fileRole =
                        repository.GetSingle<FileRoleDbModel>(x => x.ROLESID.Equals(fileRoleChangeArgs.RoleSid));
                    if(null != fileRole)
                    {
                        fileRole.ISCREATE = fileRoleChangeArgs.IsCreate;
                        fileRole.ISDELETE = fileRoleChangeArgs.IsDelete;
                        fileRole.ISOWNER = fileRoleChangeArgs.IsJustMe;
                        fileRole.ISREAD = fileRoleChangeArgs.IsRead;
                        fileRole.ISUPDATE = fileRoleChangeArgs.IsUpdate;
                        fileRole.Update();
                        if (fileRoleChangeArgs.UpdateSubFolder)
                        {
                            var subFileRoleCollection =
                                repository.GetAll<FileRoleDbModel>(
                                    x => x.FILESID.Equals(fileRole.FLAGSID) && !x.ROLESID.Equals(fileRole.ROLESID));
                            foreach (var fileRoleDbModel in subFileRoleCollection)
                            {
                                fileRoleDbModel.ISCREATE = fileRoleChangeArgs.IsCreate;
                                fileRoleDbModel.ISDELETE = fileRoleChangeArgs.IsDelete;
                                fileRoleDbModel.ISOWNER = fileRoleChangeArgs.IsJustMe;
                                fileRoleDbModel.ISREAD = fileRoleChangeArgs.IsRead;
                                fileRoleDbModel.ISUPDATE = fileRoleChangeArgs.IsUpdate;
                                fileRoleDbModel.Update();
                            }
                        }
                        var fileLogModel = new FileLogDbModel
                        {
                            LOGSID = Guid.NewGuid().ToString(),
                            LOG = string.Format("修改权限:  成功!"),
                            LOGTIME = DateTime.Now,
                            LOGTYPE = "修改权限",
                            OBJECTID = fileRole.FILESID,
                            TARGETNAME = "修改了权限!",
                            USERID = fileRole.SETUSERID,
                            USERNAME = fileRole.SETUSERNAME
                        };
                        fileLogModel.Create();
                    }
                }
                result.Result = true;
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("ChangeFileRole has problem:", ex);
                result.ResultException = BaseExceptionEnum.ChangeFileRoleException;
            }
            return result;
        }

        public ApplySubFolderRoleResult ApplySubFolderRole(ApplySubFolderRoleArgs applySubFolderRoleArgs)
        {
            var result = new ApplySubFolderRoleResult();
            try
            {
                using (var repository = new Repository())
                {
                    var current_folder =
                        repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(applySubFolderRoleArgs.FileSid));
                    var current_folderRole =
                        repository.GetSingle<FileRoleDbModel>(x => x.ROLESID.Equals(applySubFolderRoleArgs.RoleSid));
                    if(null!=current_folder && null!=current_folderRole)
                    {
                        var path = current_folder.FILEPATH;
                        if (string.IsNullOrEmpty(path))
                            path = "/" + current_folder.FILENAME;
                        var subFolderCollection =
                            repository.GetAll<FileDbModel>(x => x.FILEPATH.StartsWith(path)).Select(x=>x.FILESID);
                        var hasFolderRole =
                            repository.GetAll<FileRoleDbModel>(x => x.FLAGSID.Equals(current_folderRole.FLAGSID)).Select(x=>x.FILESID);
                        var notHasRoleFileSid = subFolderCollection.Where(x => !hasFolderRole.Contains(x));
                        notHasRoleFileSid = notHasRoleFileSid.Distinct();
                        foreach (var newRole in notHasRoleFileSid.Select(newFileRole => new FileRoleDbModel
                                                                                            {
                                                                                                FILESID = newFileRole,
                                                                                                FLAGSID = current_folderRole.FLAGSID,
                                                                                                INHERITFILESID = current_folderRole.FILESID,
                                                                                                ISALLOWALLOCATE = true,
                                                                                                ISINHERIT = true,
                                                                                                ISCREATE = current_folderRole.ISCREATE,
                                                                                                ISDELETE = current_folderRole.ISDELETE,
                                                                                                ISOWNER = current_folderRole.ISOWNER,
                                                                                                ISREAD = current_folderRole.ISREAD,
                                                                                                ISUPDATE = current_folderRole.ISUPDATE,
                                                                                                RELATIONID = current_folderRole.RELATIONID,
                                                                                                ROLESID = Guid.NewGuid().ToString(),
                                                                                                ROLETYPE = current_folderRole.ROLETYPE,
                                                                                                SETUSERID = current_folderRole.SETUSERID,
                                                                                                SETUSERNAME = current_folderRole.SETUSERNAME
                                                                                            }))
                        {
                            newRole.Create();
                        }
                    }
                }
                result.Result = true;
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("ApplySubFolderRole has problem:", ex);
                result.ResultException = BaseExceptionEnum.ApplySubFolderRoleExpcetion;
            }
            return result;
        }

        public DeleteFileRoleResult DeleteFileRole(DeleteFileRoleArgs deleteFileRoleArgs)
        {
            var result = new DeleteFileRoleResult();
            try
            {
                using (var repository = new Repository())
                {
                    var fileRole =
                        repository.GetSingle<FileRoleDbModel>(x => x.ROLESID.Equals(deleteFileRoleArgs.FileRoleSid));
                    if(null != fileRole)
                    {
                        if(deleteFileRoleArgs.DeleteSubFolderRole)
                        {
                            var current_folder =
                                repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(fileRole.FILESID));
                            var path = current_folder.FILEPATH;
                            if (string.IsNullOrEmpty(path))
                                path = "/" + current_folder.FILENAME;
                            var subFolderCollection =
                                repository.GetAll<FileDbModel>(x => x.FILEPATH.StartsWith(path)).Select(x => x.FILESID).ToList();
                            var hasFolderRole =
                                repository.GetAll<FileRoleDbModel>(x => x.FLAGSID.Equals(fileRole.FLAGSID) && subFolderCollection.Contains(x.FILESID));
                            //var subFolderRoleCollection =
                            //    repository.GetAll<FileRoleDbModel>(x => x.FLAGSID.Equals(fileRole.FLAGSID));
                            foreach (var fileRoleDbModel in hasFolderRole)
                                fileRoleDbModel.Delete();
                        }
                        fileRole.Delete();
                    }
                }
                result.Result = true;
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("DeleteFileRole has problem:", ex);
                result.ResultException = BaseExceptionEnum.DeleteFileRoleException;
            }
            return result;
        }


        public FileLogQueryCountResult GetFileLogCount(FileLogQueryArgs fileLogQueryArgs)
        {
            var result = new FileLogQueryCountResult();
            try
            {
                using (var repository = new Repository())
                {
                    result.LogCount = (from a in ActiveRecordLinq.AsQueryable<FileLogDbModel>()
                                           where (from b in ActiveRecordLinq.AsQueryable<FileDbModel>() where 
                                                      fileLogQueryArgs.FileSidCollection.Contains(b.FILESID)||
                                                       fileLogQueryArgs.FileSidCollection.Contains(b.PARENTID) select b.FILESID).Contains(a.OBJECTID)
                                          select a).Count();
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("GetFileLogCount has problem:", ex);
                result.ResultException = BaseExceptionEnum.GetFileLogCountException;
            }
            return result;
        }

        public FileLogResultCollection GetFileLog(FilelogQueryPageArgs filelogQueryPageArgs)
        {
            var result = new FileLogResultCollection();
            try
            {
                using (var repository = new Repository())
                {
                    var skipNumber = filelogQueryPageArgs.CurrentPage*filelogQueryPageArgs.SkipNumber;
                    var queryResult = (from a in ActiveRecordLinq.AsQueryable<FileLogDbModel>()
                                       where (from b in ActiveRecordLinq.AsQueryable<FileDbModel>()
                                              where
                                                  filelogQueryPageArgs.FileSidCollection.Contains(b.FILESID) ||
                                                  filelogQueryPageArgs.FileSidCollection.Contains(b.PARENTID)
                                              select b.FILESID).Contains(a.OBJECTID)
                                       select a).Skip(skipNumber).Take(filelogQueryPageArgs.SkipNumber).ToList();
                    result.Result = Mapper.Map<IList<FileLogDbModel>, List<FileLogResult>>(queryResult);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("GetFileLog has problem:", ex);
                result.ResultException = BaseExceptionEnum.GetFileLogException;
            }
            return result;
        }


        public FileRoleAddResultCollection GetFolderRoleDelegate(FileRoleAddDDelegateArgs fileRoleAddDDelegateArgs)
        {
            var result = new FileRoleAddResultCollection();
            try
            {
                CheckCache();
                using (var repository = new Repository())
                {
                    var fileRoleCollection =
                        repository.GetAll<FileRoleDbModel>(x => x.FILESID.Equals(fileRoleAddDDelegateArgs.FileSid) && x.SETUSERID.Equals(fileRoleAddDDelegateArgs.UserId));
                    result.Result = Mapper.Map<IList<FileRoleDbModel>, List<FileRoleAddResult>>(fileRoleCollection);
                    var parentCollection = fileRoleCollection.Select(x => x.INHERITFILESID).ToList();
                    var userCollectionDb =
                        fileRoleCollection.Where(x => x.ROLETYPE.Equals("0")).Select(x => x.RELATIONID).ToList();
                    var fileDbMeol = new List<FileDbModel>();
                    var userCollection = new List<UserDbModel>();
                    if (parentCollection.Any())
                        fileDbMeol = repository.GetAll<FileDbModel>(x => parentCollection.Contains(x.FILESID)).ToList();
                    if (userCollectionDb.Any())
                        userCollection = repository.GetAll<UserDbModel>(x => userCollectionDb.Contains(x.SID)).ToList();
                    var deleteObj =
                        result.Result.Where(
                            x => (x.RoleType.Equals("2") || x.RoleType.Equals("3")) && x.RelationId.Equals("-1")).ToList();
                    //foreach (var fileRoleAddResult in deleteObj)
                    //    result.Result.Remove(fileRoleAddResult);
                    foreach (var t in deleteObj)
                        result.Result.Remove(t);
                    foreach (var fileRoleModel in result.Result)
                    {
                        switch (fileRoleModel.RoleType)
                        {
                            //用户
                            case "0":
                                fileRoleModel.RelationName =
                                    userCollection.FirstOrDefault(x => x.USERID.Equals(fileRoleModel.RelationId)).NAME;
                                break;
                            //组织机构
                            case "1":
                                fileRoleModel.RelationName =
                                    cacheCompany.FirstOrDefault(x => x.Id.Equals(fileRoleModel.RelationId)).ShortName;
                                break;
                            //人员公共组
                            case "2":
                                var userGroup =
                                    cacheUserGroup.FirstOrDefault(x => !string.IsNullOrEmpty(x.Sid) && x.Sid.Equals(fileRoleModel.RelationId));
                                fileRoleModel.RelationName = userGroup.Name;
                                break;
                            //组织机构公共组
                            case "3":
                                var company =
                                    cacheCompanyGroup.FirstOrDefault(x => x.Sid.Equals(fileRoleModel.RelationId));
                                fileRoleModel.RelationName = company.Name;
                                break;
                            //任何人
                            case "5":
                                fileRoleModel.RelationName = "AnyOne";
                                break;
                        }
                        if (fileRoleModel.IsInherit)
                            fileRoleModel.InheritFileName =
                                fileDbMeol.FirstOrDefault(x => x.FILESID.Equals(fileRoleModel.InheritFileSId)).FILENAME;
                    }
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("GetFolderRoleDelegate has problem:", ex);
                result.ResultException = BaseExceptionEnum.GetFolderRoleException;
            }
            return result;
        }


        public FileResultCollection SearchFile(FileSearchArgs fileSearchArgs)
        {
            var result = new FileResultCollection();
            try
            {
                using (var repository = new Repository())
                {
                    var query = from a in ActiveRecordLinq.AsQueryable<FileDbModel>() where a.OWNERID.Equals(fileSearchArgs.CompanyId) select a;
                    if (!string.IsNullOrEmpty(fileSearchArgs.FileName))
                        query = query.Where(x => x.FILENAME.Contains(fileSearchArgs.FileName));
                    if (!string.IsNullOrEmpty(fileSearchArgs.FileAuth))
                        query = query.Where(x => x.CREATOR.Contains(fileSearchArgs.FileAuth));
                    if (fileSearchArgs.BeginTime != fileSearchArgs.EndTime && fileSearchArgs.BeginTime < fileSearchArgs.EndTime)
                        query =
                            query.Where(
                                x => x.CREATETIME < fileSearchArgs.EndTime && x.CREATETIME > fileSearchArgs.BeginTime);
                    IList<FileDbModel> queryResult = query.ToList();
                    result.FileCollection = Mapper.Map<IList<FileDbModel>, List<FileResult>>(queryResult);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("SearchFile has problem:", ex);
                result.ResultException = BaseExceptionEnum.SearchFileException;
            }
            return result;
        }


        public CheckFileResult CheckFile(CheckFileUploadingArgs checkFileUploadingArgs)
        {
            var result = new CheckFileResult {EnumResult = FileCheckEnum.CreateFileSuccess};
            try
            {
                using (var repository = new Repository())
                {
                    var current_user =
                        repository.GetSingle<UserDbModel>(x => x.USERID.Equals(checkFileUploadingArgs.UserId));
                    var current_folder =
                        repository.GetSingle<FileDbModel>(
                            x => x.FILESID.Equals(checkFileUploadingArgs.FolderId) && x.ISFILE == false);
                    var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_folder.OWNERID));
                    
                    var hasFileInServer =
                        repository.GetSingle<FileDbModel>(
                            x =>
                            x.ISFILE && x.PARENTID.Equals(checkFileUploadingArgs.FolderId) &&
                            x.FILENAME.Equals(checkFileUploadingArgs.FileName));
                    if(null != hasFileInServer)
                        result.FileSid = hasFileInServer.FILESID;
                    var folderPath = current_comapny.SHORTNAME + current_folder.FILEPATH;
                    folderPath = folderPath.Replace("/", @"\");
                    if (string.IsNullOrEmpty(current_folder.FILEPATH))
                        folderPath += (@"\" + current_folder.FILENAME);
                    var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath) + @"\" +
                                   checkFileUploadingArgs.FileName;
                    var uplaodingName = filePath + GlobalVariable.FileTempExtension;
                    if (File.Exists(uplaodingName))
                        result.EnumResult = FileCheckEnum.ServerHasFileUploading;
                    else
                    {
                        File.Create(uplaodingName).Close();
                        File.Open(uplaodingName, FileMode.Open, FileAccess.Write, FileShare.Write).SetLength(
                            checkFileUploadingArgs.FileLength);
                        //if(File.Exists(filePath) && checkFileUploadingArgs.IsOverUpload)
                        //{
                        //   // File.WriteAllText(filePath, string.Empty);
                        //    File.Create(uplaodingName).Close();
                        //    File.OpenWrite(uplaodingName).SetLength(checkFileUploadingArgs.FileLength);
                        //}
                        //else
                        //{
                        //    File.Create(uplaodingName).Close();
                        //    File.Open(uplaodingName, FileMode.Open, FileAccess.Write, FileShare.Write).SetLength(
                        //        checkFileUploadingArgs.FileLength);
                        //}
                        result.ServerFilePath = filePath;
                    }
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CheckFile has problem:", ex);
            }
            return result;
        }


        public void DeleteUploadingFile(DeleteUploadingFileArgs deleteUploadingFileArgs)
        {
            try
            {
                var filePath = deleteUploadingFileArgs.FileServerPath + GlobalVariable.FileTempExtension;
                if(File.Exists(filePath))
                    File.Delete(filePath);
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("DeleteUploadingFile has problem:", ex);
            }
        }


        public void UploadingFileSuccess(UploadingSuccessArgs uploadingSuccessArgs)
        {
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(uploadingSuccessArgs.UserId));
                    var current_folder = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(uploadingSuccessArgs.FolderId));
                    var hasFile = repository.GetSingle<FileDbModel>(x => x.PARENTID.Equals(uploadingSuccessArgs.FolderId) && uploadingSuccessArgs.FileName.Equals(x.FILENAME));
                    if (null != hasFile)
                    {
                        hasFile.UPDATER = current_user.NAME;
                        hasFile.UPDATETIME = DateTime.Now;
                        hasFile.UPDATERID = current_user.USERID;
                        hasFile.Update();
                        var fileLogModel = new FileLogDbModel
                        {
                            LOGSID = Guid.NewGuid().ToString(),
                            LOG = string.Format("更新文件: {0} 成功!", hasFile.FILEPATH + @"\" + hasFile.FILENAME),
                            LOGTIME = DateTime.Now,
                            LOGTYPE = "更新",
                            OBJECTID = hasFile.FILESID,
                            TARGETNAME = hasFile.FILEPATH + @"\" + hasFile.FILENAME,
                            USERID = current_user.SID,
                            USERNAME = current_user.NAME
                        };
                        fileLogModel.Create();
                    }
                    else
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_folder.OWNERID));
                        // kill target file, if already exists
                        var folderPath = current_comapny.SHORTNAME + current_folder.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_folder.FILEPATH))
                            folderPath += (@"\" + current_folder.FILENAME);
                        var logPath = folderPath;
                        var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath) + "/" + uploadingSuccessArgs.FileName;
                        var fileDbModel = new FileDbModel
                        {
                            FILESID = Guid.NewGuid().ToString(),
                            FILENAME = uploadingSuccessArgs.FileName,
                            PARENTID = uploadingSuccessArgs.FolderId,
                            FILEPATH = string.IsNullOrEmpty(current_folder.FILEPATH) ? "/" + current_folder.FILENAME : current_folder.FILEPATH,
                            FILETYPE = false,
                            OWNERID = current_comapny.SID,
                            ISSHARE = false,
                            ISFILE = true,
                            CREATOR = current_user.NAME,
                            CREATORID = current_user.SID,
                            CREATETIME = DateTime.Now,
                            UPDATER = current_user.NAME,
                            UPDATERID = current_user.SID,
                            UPDATETIME = DateTime.Now,
                            FILEMARK = FileUtility.Md5File(filePath),
                            FILESORT = 1,
                            FILESIZE = uploadingSuccessArgs.FileLength
                        };
                        fileDbModel.Create();
                        var folderRoleCollection = repository.GetAll<FileRoleDbModel>(x => x.FILESID.Equals(uploadingSuccessArgs.FolderId));
                        foreach (var subFileRole in folderRoleCollection.Select(folderRole => new FileRoleDbModel
                        {
                            FILESID = fileDbModel.FILESID,
                            FLAGSID = folderRole.FLAGSID,
                            INHERITFILESID = folderRole.INHERITFILESID,
                            ISALLOWALLOCATE = true,
                            ISCREATE = folderRole.ISCREATE,
                            ISDELETE = folderRole.ISDELETE,
                            ISINHERIT = true,
                            ISOWNER = folderRole.ISOWNER,
                            ISREAD = folderRole.ISREAD,
                            ISUPDATE = folderRole.ISUPDATE,
                            RELATIONID = folderRole.RELATIONID,
                            ROLESID = Guid.NewGuid().ToString(),
                            ROLETYPE = folderRole.ROLETYPE,
                            SETUSERID = folderRole.SETUSERID,
                            SETUSERNAME = folderRole.SETUSERNAME
                        }))
                        {
                            subFileRole.Create();
                        }
                        var fileLogModel = new FileLogDbModel
                        {
                            LOGSID = Guid.NewGuid().ToString(),
                            LOG = string.Format("上传文件: {0} 成功!", logPath + @"\" + uploadingSuccessArgs.FileName),
                            LOGTIME = DateTime.Now,
                            LOGTYPE = "上传",
                            OBJECTID = fileDbModel.FILESID,
                            TARGETNAME = logPath + @"\" + uploadingSuccessArgs.FileName,
                            USERID = current_user.SID,
                            USERNAME = current_user.NAME
                        };
                        fileLogModel.Create();
                    }
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("UploadingFileSuccess has problem:", ex);
            }
        }


        public DownloadingCheckFileResultCollection CheckFileInfomation(DownlaodingCheckFilesArgs downlaodingCheckFilesArgs)
        {
            try
            {
                var result = new DownloadingCheckFileResultCollection
                                 {DownloadingCheckFiles = new List<DownloadingCheckFileResult>()};
                using (var repository = new Repository())
                {
                    foreach (var fileSid in downlaodingCheckFilesArgs.FileSidCollection)
                    {
                        var fileInfo = new DownloadingCheckFileResult {FileSid = fileSid};
                        var currentFile = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(fileSid));
                        if(null == currentFile)
                            fileInfo.FileException = FileExceptionEnum.FileNotFind;
                        else
                        {
                            var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(currentFile.OWNERID));
                            var folderPath = current_comapny.SHORTNAME + currentFile.FILEPATH;
                            folderPath = folderPath.Replace("/", @"\");
                            if (string.IsNullOrEmpty(currentFile.FILEPATH))
                                folderPath += (@"\" + currentFile.FILENAME);
                            var filePath = Path.Combine(GlobalString.System_Config_String.FileDiskPath, folderPath) + "/" +
                                           currentFile.FILENAME;
                            var localFileInfo = new FileInfo(filePath);
                            if (!localFileInfo.Exists)
                                fileInfo.FileException = FileExceptionEnum.FileNotFind;
                            else
                            {
                                fileInfo.FileName = localFileInfo.Name;
                                fileInfo.FileServerPath = localFileInfo.FullName;
                                fileInfo.FileSize = localFileInfo.Length;
                                fileInfo.FileException = FileExceptionEnum.FileExists;
                            }
                        }
                        result.DownloadingCheckFiles.Add(fileInfo);
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CheckFileInfomation has problem:", ex);
                throw ex;
            }
        }


        public void DownloadingFileSuccess(DownloadingSuccessArgs downloadingSuccessArgs)
        {
            try
            {
                using (var repository = new Repository())
                {
                    var current_user = repository.GetSingle<UserDbModel>(x => x.USERID.Equals(downloadingSuccessArgs.UserId));
                    var current_file = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(downloadingSuccessArgs.FileSid));
                    if (null != current_user && null != current_file)
                    {
                        var current_comapny = repository.GetSingle<Company>(x => x.SID.Equals(current_file.OWNERID));
                        // kill target file, if already exists
                        var folderPath = current_comapny.SHORTNAME + current_file.FILEPATH;
                        folderPath = folderPath.Replace("/", @"\");
                        if (string.IsNullOrEmpty(current_file.FILEPATH))
                            folderPath += (@"\" + current_file.FILENAME);
                        var logPath = folderPath;
                        var fileLogModel = new FileLogDbModel
                        {
                            LOGSID = Guid.NewGuid().ToString(),
                            LOG =
                                string.Format("下载文件: {0} 成功!", logPath + @"\" + current_file.FILENAME),
                            LOGTIME = DateTime.Now,
                            LOGTYPE = "下载",
                            OBJECTID = current_file.FILESID,
                            TARGETNAME = logPath + @"\" + current_file.FILENAME,
                            USERID = current_user.SID,
                            USERNAME = current_user.NAME
                        };
                        fileLogModel.Create();
                    }
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("DownloadingFileSuccess has problem:", ex);
                throw ex;
            }
        }

        private bool CheckUploadingFile(string filePath)
        {
            var tempUploadPath = filePath + GlobalVariable.FileTempExtension;
            return File.Exists(tempUploadPath);
        }


        public DepartmentSizeResultCollection GetDepartmentSizeCollection()
        {
            var result = new DepartmentSizeResultCollection();
            try
            {
                using (var repository = new Repository())
                {
                    var queryResult = repository.GetAll<FileDepartsizeDbModel>();
                    if (null != queryResult)
                        result.DepartmentSizeResults = Mapper.Map<IList<FileDepartsizeDbModel>, List<DepartmentSizeResult>>(queryResult);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("GetDepartmentSizeCollection has problem:", ex);
                return new DepartmentSizeResultCollection();
            }
            return result;
        }

        public int GetDepartmentSizeMB(string departmentId)
        {
            int result;
            try
            {
                using (var repository = new Repository())
                {
                    var queryResult = repository.GetSingle<FileDbModel>(x => x.FILESID.Equals(departmentId));
                    var query = (from a in ActiveRecordLinq.AsQueryable<FileDbModel>()
                                 where a.OWNERID.Equals(queryResult.OWNERID) && a.ISFILE
                                 select a.FILESIZE).Sum(x => x);
                    result = (int)(query / 1024);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("GetDepartmentSizeMB has problem:", ex);
                return 0;
            }
            return result;
        }
    }
}